import java.util.ArrayList;
public class Solution {
    public ArrayList<Integer> printMatrix(int [][] matrix) {
        //思想：定义四个边界变量，不断收缩矩阵边界
        //创建ArrayList
        ArrayList<Integer> list = new ArrayList<>();
        //判断matrix是否为空，矩阵长度是否为0
        if(matrix == null || matrix.length == 0 || matrix[0].length == 0){
            return list;
        }
        //定义上下左右四个边界
        int up = 0;
        int down = matrix.length-1;
        int left = 0;
        int right = matrix[0].length-1;
        while(true){
            for(int col = left; col <= right; col++){
                list.add(matrix[up][col]);
            }
            //向下逼近
            up++;
            //判断是否越界
            if(up > down){
                break;
            }
            
            for(int row = up; row <= down; row++){
                list.add(matrix[row][right]);
            }
            //向左逼近
            right--;
            if(left > right){
                break;
            }
            
            for(int col = right; col >= left; col--){
                list.add(matrix[down][col]);
            }
            //向上逼近
            down--;
            if(up > down){
                break;
            }
            
            for(int row = down; row >= up; row--){
                list.add(matrix[row][left]);
            }
            //向右逼近
            left++;
            if(left > right){
                break;
            }
        }
        return list;
    }
}